import { traceCustomEvent } from './trace'
import md5 from 'md5'
import Axios from 'axios'
import { getUrlQuery } from '@/utils'
import { sortASCII } from '@/request'
import $zpt from 'jquery'

export interface Options {
  baseUrl: string
  channelCode?: string
  memberCode?: string
  channelId?: string
  memberId?: string
  userId?: string
  version: string
}
export interface EventUiEnterResType {}

// header处理
Axios.interceptors.request.use(
  function (config: any) {
    // let params = config.data || {}
    const method = config.method ? config.method.toLowerCase() : 'get'
    let params = (method === 'get' ? config.params : config.data) || {}

    params['ts'] = new Date().getTime()
    params = sortASCII(params, true)

    if (method === 'get') {
      config.params = params
      // get验签台号要求
      Object.keys(params).map((key) => {
        if (typeof params[key] == 'number') params[key] = String(params[key])
      })
      config.headers['sk'] = md5(JSON.stringify(params))
    } else {
      config.data = params
      config.headers['sk'] = md5(JSON.stringify(params))
    }

    return config
  },
  function (error) {
    return Promise.reject(error)
  },
)

export default class EventSDK {
  flag: boolean
  options: Options
  baseUrl: string
  userId: any
  data: any
  timeoutData: number
  timer: any
  flsVersion: {
    v3: number
    v1: number
  }
  isPopupClose: boolean
  queryTimes: number
  eventsInitialized: boolean
  constructor(options: Options) {
    this.options = options
    this.flag = false
    this.isPopupClose = false
    this.data = {}
    this.timeoutData = 3
    this.timer = null
    this.queryTimes = 1
    this.flsVersion = {
      v3: 3,
      v1: 1,
    }
    this.eventsInitialized = false
    this.baseUrl = options.baseUrl || ''
    this.userId = options.userId || ''
  }

  async init(baseUrl: any, options: any) {
    options.baseUrl = baseUrl
    this.baseUrl = baseUrl
    this.options = options
    await this.fetchData()
    if (!this.eventsInitialized) {
      this.initEvent(options)
      this.eventsInitialized = true
    }
  }

  // 初始化事件
  initEvent(options: any) {
    const that = this
    const { version, MyCardPageUrl } = options

    //立即领取点击事件
    $zpt(document).on('click', '#rightPopupModalBtn', function () {
      if (that.flag) return

      // 7020 7021 7022 渠道id 跳转到详情页
      //@ts-ignore
      const { userId, channelId } = getUrlQuery()
      if (['7020', '7021', '7022'].includes(channelId)) {
        const { origin, pathname } = location
        const { id, rightsType } = that.data?.popRightsVO
        // 此处权益与福利社中权益类型不一致  1:权益=>2   2:外链=>3
        let type = 2
        if (rightsType == 2) {
          type = 3
        }
        window.location.href = `${origin}${pathname}rightsDetail?rightId=${id}&rightType=${type}&userId=${userId}&channelId=${channelId}&isPopup=1`
        return
      }

      if (that.data.frontendStyle == 'popupActivity') {
        that.goActiveMarketing(options)
      } else {
        that.rightsReceive(options)
      }
    })

    $zpt(document).on('touchmove', '#rightPopupModalLayer', function (event) {
      event.preventDefault()
      return false
    })

    $zpt(document).on('touchmove', '#rightSuccessModalLayer', function (event) {
      event.preventDefault()
      return false
    })

    // 首页弹窗关闭
    $zpt(document).on('click', '#rightPopupModalCloseBtn', function () {
      if (that.flag) return
      that.rightsClose(options, that.data)
      traceCustomEvent(that.options, {
        message: 'right-popup-close',
        params: {
          eventName: '弹框关闭',
        },
      })
    })

    // 首页弹窗打开
    $zpt(document).on('click', '#rightPopupFloatModal', function () {
      $zpt('#rightPopupFloatModal').remove()
      that.isPopupClose = true
      that.validRightPopModal(that.data, false)
      traceCustomEvent(that.options, {
        message: 'right-popup-icon-click',
        params: {
          eventName: 'icon点击弹起',
        },
      })
    })

    //去卡券页
    $zpt(document).on('click', '#rightSuccessModalToMyOrder', function () {
      if (version == 'v3') {
        window.location.href = `${window.location.origin}${window.location.pathname}myRights${window.location.search}`
      } else if (version == 'v1') {
        const isProd = that.baseUrl.indexOf('fls1.fuxiaoli.com') == -1 ? false : true
        window.location.href = `${that.baseUrl}${isProd ? 'fls1-ui' : 'fls-ui'}/${MyCardPageUrl}`
      }
    })

    $zpt(document).on('click', '#rightSuccessModalBtn', function () {
      $zpt('#rightSuccessModal').remove()
      $zpt('body').removeClass('v-body-hide')
      $zpt('html').removeClass('v-body-hide')
      that.timeoutData = 3
      clearInterval(that.timer)
      that.timer = null
    })

    // 监听浏览器关闭事件,清除localStorage
    // 监听页面隐藏和可见性变化
    document.addEventListener('visibilitychange', function () {
      if (document.visibilityState === 'hidden') {
        localStorage.removeItem('rightPopupFloatModal')
      }
    })

    // 监听页面卸载
    window.addEventListener('pagehide', function () {
      localStorage.removeItem('rightPopupFloatModal')
    })

    // 监听应用退出
    window.addEventListener('unload', function () {
      localStorage.removeItem('rightPopupFloatModal')
    })
  }

  async fetchData() {
    this.flag = false
    const { channelId, memberId, userId, version, channelCode, memberCode } = this.options
    // let res = {"code":0,"data":{"isClose":1,"eventBaseId":754,"eventCode":"4d09f9d7a2da4aaa89a4124f7660cdbc","floatingWindowsDescription":"","floatingWindowsImg":"https://st1.fuxiaoli.com/true/3bf26fdf00dc458ca0bdd97de5e9f4b9.png","frontendStyle":"popupRights ","isCurrent":true,"popupBackgroundImg":"https://st1.fuxiaoli.com/true/e365362373b74b54b6cacb7d0ce1e136.png ","popupBaseImg":"https://st1.fuxiaoli.com/true/8198c89596444cf7af791b251ae81cf7.png ","popupButtonImg":"https://st1.fuxiaoli.com/true/a1cb265c33cd40fca693c33831a64ab7.png ","popupDescription":"","popRightsVO":{"code":"","couponType":{"index":0,"oridnal":0,"name":"NONE","label":"非优惠券"},"description":"","id":2472,"imageUrl":"https://st1.fuxiaoli.com/right/8a43cc2bf3b340b99648b45a456ebecd.png ","logoUrl":"https://st1.fuxiaoli.com/right/93bdf4273c4a46aba80a8f1904732990.png ","name":"假码直充jd ","packId":0,"receiveType":{"index":1,"oridnal":1,"name":"MEMBER","label":"会员直接领取"},"rightsType":1},"popupTitleImg":"https://st1.fuxiaoli.com/true/3cb7e3db6ffc4195b2bb3c0add0ba35b.png ","receiveSucceedBackgroundImg":"https://st1.fuxiaoli.com/true/a76989e48b1d43a99ee5a42bba85da08.png ","receiveSucceedButtonImg":"https://st1.fuxiaoli.com/true/4b0722e763fb46d892d5b74321cc9878.png ","ruleDescription":"","themeColor":"#ff0000 "},"msg":""}
    // let resData = res.data
    // this.data = res.data
    // this.validRightPopModal(resData);
    console.log('-------192------', this.baseUrl, this.flsVersion, this.flsVersion[version])
    const today = new Date().toISOString().split('T')[0]
    await Axios.post(this.baseUrl + 'api3/channel/elite/right/popupSeveralRights', {
      channelId,
      memberId,
      userId,
      channelCode,
      memberCode,
      userType: this.flsVersion[version],
    }).then((res) => {
      let date: any
      if (res.data?.data?.frontendStyle == 'popupActivity') {
        date = localStorage.getItem('fls_right_popup_data')
      }
      if (res.data?.code == 0) {
        const resData = res.data?.data
        this.data = {}
        if (!resData) {
          if (this.queryTimes > 0) {
            this.queryTimes--
            setTimeout(() => this.fetchData(), 1000)
          }
        } else {
          this.data = resData
          if (resData?.isClose == 1) {
            this.isPopupClose = false
          }
          if (resData?.frontendStyle == 'popupActivity' && date != today) {
            // 当天首次访问
            this.isPopupClose = true
          } else {
            // 当天非首次访问
            this.isPopupClose = false
          }
          this.preloadImg(resData)
          this.validRightPopModal(resData, true)
        }
      } else if (this.queryTimes > 0) {
        this.queryTimes--
        setTimeout(() => this.fetchData(), 1000)
      }
    })
  }

  rightsReceive(options: any) {
    this.flag = true
    const { channelId, memberId, userId, version, channelCode, memberCode } = options
    Axios.post(this.baseUrl + 'api3/channel/elite/right/popupRightsReceive', {
      channelId,
      memberId,
      userId,
      channelCode,
      memberCode,
      userType: this.flsVersion[version],
      rightId: this.data?.popRightsVO?.id,
      rightType: this.data?.popRightsVO?.rightsType,
    }).then((res) => {
      $zpt('#rightPopupModal').remove()
      $zpt('body').removeClass('v-body-hide')
      $zpt('html').removeClass('v-body-hide')
      if (res.data?.code == 0) {
        this.renderRightPopSuccessModal(this.data)
        this.startTimeOut()
      } else {
        this.toast({ content: res.data?.msg })
      }
      setTimeout(() => {
        this.flag = false
      })
      traceCustomEvent(this.options, {
        message: 'right-popup-receive',
        params: {
          eventName: '权益领取',
          rightId: this.data?.popRightsVO?.id,
          rightType: this.data?.popRightsVO?.rightsType,
        },
      })
    })
  }
  goActiveMarketing(options: any) {
    this.flag = true
    const { channelCode, memberCode } = options
    window.location.href = `${window.location.origin}/fls-common-ui/activitysMarketing?memberCode=${memberCode}&channelCode=${channelCode}`
    // 记录当前日期
    localStorage.setItem('fls_right_popup_data', new Date().toISOString().split('T')[0])
    $zpt('#rightPopupModal').remove()
    $zpt('body').removeClass('v-body-hide')
    $zpt('html').removeClass('v-body-hide')
    this.renderRightPopMiniModal(this.data)
    setTimeout(() => {
      this.flag = false
    })
  }
  toast(config: any) {
    if (!config.content) {
      return
    }
    const str = `
    <div id="poupMessageTips" style="font-size: 3.6vw; color: #fff; line-height: 6vw; padding: 0 6vw;z-index: 19; text-align: center; position: fixed; left: 0; right: 0; top: 46%; transform: translateY(-50%); -webkit-transform: translateY(-50%);',">
      <p style="padding: 2vw 7.8vw; background: rgba(0, 0, 0, 0.5); display: inline-block; border-radius: 1vw;">${config.content}</p>
    </div>
    `
    if ($zpt('#poupMessageTips').length <= 0) {
      $zpt('body').append(str)
    }
    let timt_res = 1000
    if (typeof config.duration === 'number' && !!config.duration) timt_res = config.duration
    setTimeout(function () {
      $zpt('#poupMessageTips').remove()
    }, timt_res)
  }
  rightsClose(options: any, data: any) {
    if (data?.isClose == 1) {
      $zpt('#rightPopupModal').remove()
      $zpt('body').removeClass('v-body-hide')
      $zpt('html').removeClass('v-body-hide')
      this.renderRightPopMiniModal(data)
    } else {
      this.flag = true
      if (data?.frontendStyle == 'popupActivity') {
        // // 记录当前日期
        localStorage.setItem('fls_right_popup_data', new Date().toISOString().split('T')[0])
      }
      const { channelId, memberId, userId, version, channelCode, memberCode } = options
      Axios.post(this.baseUrl + 'api3/channel/elite/right/popupRightsClose', {
        channelId,
        memberId,
        userId,
        channelCode,
        memberCode,
        userType: this.flsVersion[version],
        rightId: data?.popRightsVO?.id,
        rightType: data?.popRightsVO?.rightsType,
      }).then((res) => {
        if (res) {
          this.flag = false
          $zpt('#rightPopupModal').remove()
          $zpt('body').removeClass('v-body-hide')
          $zpt('html').removeClass('v-body-hide')
          this.renderRightPopMiniModal(data)
        }
      })
    }
  }

  validRightPopModal(data: any, first?: any) {
    try {
      // 判断今日是否弹过
      if (data?.isClose == 0 || this.isPopupClose == true) {
        //0未关闭 1已关闭
        this.renderRightPopModal(data, first)
      } else {
        this.renderRightPopMiniModal(data)
      }
    } catch (error) {}
  }

  startTimeOut() {
    this.timeoutData = 3
    this.timer = setInterval(() => {
      this.timeoutData--
      if (this.timeoutData <= 0) {
        $zpt('#rightSuccessModal').remove()
        $zpt('body').removeClass('v-body-hide')
        $zpt('html').removeClass('v-body-hide')
        if ($zpt('#rightPopupFloatModal').length > 0) {
          $zpt('#rightPopupFloatModal').remove()
        }
        clearInterval(this.timer)
        this.timer = null
      }
      $zpt('#rightSuccessModalTimeoutData').text(this.timeoutData)
    }, 1000)
  }

  // 首页弹窗
  renderRightPopModal(data: any, first: any) {
    if (data?.frontendStyle != 'popupActivity') {
      if (!data?.popRightsVO) return
    }
    const str = `
    <div id="rightPopupModal">
      <div id="rightPopupModalLayer" style="z-index: 21;position: fixed; left: 0; top: 0; width: 100vw; height: 100vh; background-color: rgba(0, 0, 0, 0.7);overflow:hidden;"></div>
      <div style="position: absolute; z-index: 22; top:36vw; left:50%; transform: translateX(-50%); width: 83.7vw; height: 95.5vw; display: flex; flex-flow: column nowrap; align-items: center; box-sizing: border-box;">
        <div style="width: 100%;text-align: right;margin-right: -36px;position: relative;">
          <img
            id="rightPopupModalCloseBtn"
            style="z-index: 23;width: 8.6vw; height: 8.6vw;position: absolute;top: -5vw;right: 5vw;"
            src="https://fst1.fuxiaoli.com/images/nfls/rights-close2.png"
            alt=""
          />
        </div>
        <div style="position: relative;height: 700px;">
          <img
            style="width: 69vw;display: block;margin: 0 auto;object-fit: cover;"
            src="${data?.popupTitleImg}"
            alt=""
          />
          <div
            style="position: relative;width: 79vw;height: 82vw;background-size: 100% 100%;margin-top: -9vw;background-image: url(${
              data?.popupBackgroundImg
            })"
          >
            <div style="position: absolute;top: 26vw;left: 29.3vw;font-weight: 500;font-size: 5vw;color: #a96e37;">会员专享</div>
            <div style="position: absolute;width: 58vw;top: 41.5vw;left: 10.5vw;display: flex;align-items: center;justify-content: space-between;">
              <img style="width: 20vw;height: 20vw;border-radius: 10px;object-fit: cover;" src="${
                data?.popRightsVO?.logoUrl || data?.popRightsVO?.imageUrl
              }" alt="" />
              <div style="width: 35vw;height: 20vw;overflow: hidden;font-size: 4.4vw;color: #da2f2f;word-break: break-all;text-align: center;font-weight: bold;padding: 0 2vw;display: flex;">
                <div style="max-height: 13vw;word-break: break-all;align-self: center;margin: auto;overflow: hidden;text-overflow: ellipsis;display: -webkit-box; -webkit-line-clamp:2;-webkit-box-orient: vertical;">${
                  data?.popRightsVO?.name
                }</div>
              </div>
            </div>
            <img
              id="rightPopupModalBtn"
              style="position: absolute;top: 68.5vw;width: 36vw;object-fit: cover;left: 50%;transform: translateX(-50%);"
              src="${data?.popupButtonImg}"
              alt=""
            />
          </div>
        </div>
      </div>
    </div>
    `
    const activeStr = `
       <div id="rightPopupModal">
    <div
      id="rightPopupModalLayer"
      style="
        z-index: 21;
        position: fixed;
        left: 0;
        top: 0;
        width: 100vw;
        height: 100vh;
        background-color: rgba(0, 0, 0, 0.7);
        overflow: hidden;
      "
    ></div>
    <div
      style="
        position: absolute;
        z-index: 22;
        top: 36vw;
        left: 50%;
        transform: translateX(-50%);
        width: 83.7vw;
        height: 95.5vw;
        display: flex;
        flex-flow: column nowrap;
        align-items: center;
        box-sizing: border-box;
      "
    >
      <div style="position: relative; height: 700px">
        <img
          id="rightPopupModalBtn"
          style="
            position: relative;
            width: 80vw;
            height: 93vw;
            background-size: 100% 100%;
            margin-top: -9vw;
          "
          src="${data?.popupBaseImg}"
          alt=""
        />
      </div>
      <div style="width: 100%; position: relative">
        <img
          id="rightPopupModalCloseBtn"
          style="
            z-index: 23;
            width: 8.6vw;
            height: 8.6vw;
            position: absolute;
            top: 0vw;
            left: 50%;
            transform: translateX(-50%);
          "
          src="https://fst1.fuxiaoli.com/images/nfls/rights-close2.png"
          alt=""
        />
      </div>
    </div>
  </div>
    `
    const node = data?.frontendStyle == 'popupActivity' ? activeStr : str
    // if ($zpt('#rightPopupModal').length <= 0) {
    $zpt('#rightPopupModal').remove()
    $zpt('body').append(node)
    $zpt('body').addClass('v-body-hide')
    $zpt('html').addClass('v-body-hide')
    // }

    if (first) {
      traceCustomEvent(this.options, {
        message: 'right-popup-auto',
        params: {
          eventName: '弹框自动弹起',
        },
      })
    }
  }

  // 首页浮窗
  renderRightPopMiniModal(data: any) {
    if (!data?.floatingWindowsImg) {
      this.renderRightPopMiniModalAgain()
      return
    }
    let t = '80%'
    const storedModal = localStorage.getItem('rightPopupFloatModal')
    const rightPopupFloatModal = storedModal ? JSON.parse(storedModal) : null
    if (rightPopupFloatModal) {
      t = rightPopupFloatModal.top
    }

    // translateX(14.5vw);
    const str = `
    <div id="rightPopupFloatModal" style="position: fixed;z-index: 20;top: ${t};right: 0;transform: translateX(0);transition: transform 0.2s;width: 28vw;height: 9vw;background: #ffdb4b;border-radius: 33px 0px 0px 33px;border: 0.6vw solid #ffffff;">
      <div style="position: relative;display: flex;justify-content: space-between;align-items: center;">
        <img id="MiniModalImg" style="width: 11vw;margin-left: 1.2vw;margin-top: -4vw;" src="${data?.floatingWindowsImg}" alt="" />
        <span style="font-weight: 600;font-size: 3.6vw;color: #333333;text-align: left;font-style: normal;display: block;margin-right: 1.8vw;margin-top: 1vw;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">领福利</span>
      </div>
    </div>
    `
    const activityStr = `
      <div
        id="rightPopupFloatModal"
        style="
          position: fixed;
          z-index: 20;
          top: ${t};
          right: 0;
          transform: translateX(0);
          transition: transform 0.2s;
          width: 24.5vw;
          height: 23vw;
        "
      >
        <img
        id="MiniModalImg"
          style="width: 100%; height: 100%"
          src="${data?.floatingWindowsImg}"
          alt=""
        />
      </div>
    `
    // if ($zpt('#rightPopupFloatModal').length <= 0) {
    const node = data?.frontendStyle == 'popupActivity' ? activityStr : str
    $zpt('#rightPopupFloatModal').remove()
    $zpt('body').append(node)

    try {
      this.renderRightPopMiniModalImgOnError(() => {
        this.renderRightPopMiniModalRefresh(data?.floatingWindowsImg)
      })
    } catch (error) {}
    // }
    // 拖动逻辑
    this.enableRightPopupFloatModalDrag()
  }

  // 图片加载失败onError函数处理
  renderRightPopMiniModalImgOnError(callback) {
    if ($zpt('#rightPopupFloatModal').length > 0) {
      if ($zpt('#rightPopupFloatModal').find('#MiniModalImg').length > 0) {
        const imgEl = $zpt('#rightPopupFloatModal').find('#MiniModalImg')[0]
        imgEl.onerror = function () {
          if ($zpt('#rightPopupFloatModal').length > 0) {
            callback && callback()
          }
        }
      }
    }
  }

  // 没有测试验证环境
  // 首次加载图片不显示，添加的方法
  renderRightPopMiniModalAgain() {
    const { channelId, memberId, userId, version, channelCode, memberCode } = this.options
    Axios.post(this.baseUrl + 'api3/channel/elite/right/popupSeveralRights', {
      channelId,
      memberId,
      userId,
      channelCode,
      memberCode,
      userType: this.flsVersion[version],
    }).then((res) => {
      if (res.data?.code == 0) {
        const resData = res.data?.data

        let floatImg = 'https://st1.fuxiaoli.com/true/3bf26fdf00dc458ca0bdd97de5e9f4b9.png'
        if (resData && resData.floatingWindowsImg) {
          floatImg = resData.floatingWindowsImg
        }

        this.renderRightPopMiniModalRefresh(floatImg)
      }
    })
  }

  renderRightPopMiniModalRefresh(floatImg) {
    let t = '80%'
    const storedModal = localStorage.getItem('rightPopupFloatModal')
    const rightPopupFloatModal = storedModal ? JSON.parse(storedModal) : null
    if (rightPopupFloatModal) {
      t = rightPopupFloatModal.top
    }
    const str = `
      <div id="rightPopupFloatModal" style="position: fixed;z-index: 20;top: ${t};right: 0;transform: translateX(0);transition: transform 0.2s;width: 28vw;height: 9vw;background: #ffdb4b;border-radius: 33px 0px 0px 33px;border: 0.6vw solid #ffffff;">
        <div style="position: relative;display: flex;justify-content: space-between;align-items: center;">
          <img style="width: 11vw;margin-left: 1.2vw;margin-top: -4vw;" src="${floatImg}" alt="" />
          <span style="font-weight: 600;font-size: 3.6vw;color: #333333;text-align: left;font-style: normal;display: block;margin-right: 1.8vw;margin-top: 1vw;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">领福利</span>
        </div>
      </div>
    `
    if ($zpt('#rightPopupFloatModal').length > 0) $zpt('#rightPopupFloatModal').remove()
    $zpt('body').append(str)
    // 拖动逻辑
    this.enableRightPopupFloatModalDrag()
  }

  // 加载图片
  preloadImg(data) {
    try {
      if (data?.floatingWindowsImg) {
        const floatImg = new Image()
        floatImg.src = data.floatingWindowsImg
        floatImg.onload = () => {
          if ($zpt('#rightPopupFloatModal').length > 0) {
            this.renderRightPopMiniModalImgOnError(() => {
              this.renderRightPopMiniModalRefresh(data.floatingWindowsImg)
            })
          }
        }
      }
    } catch (error) {}
  }

  //弹框领取成功页
  renderRightPopSuccessModal(data: any) {
    const str = `
    <div id="rightSuccessModal">
      <div id="rightSuccessModalLayer" style="z-index: 21;position: fixed; left: 0; top: 0; width: 100vw; height: 100vh; background-color: rgba(0, 0, 0, 0.7);overflow:hidden;"></div>
      <div style="position: absolute; z-index: 21; top:50vw; left:50%; transform: translateX(-50%); width: 83.7vw; height: 95.5vw; display: flex; flex-flow: column nowrap; align-items: center; box-sizing: border-box;">
        <div style="position: relative;line-height: 1;">
          <img style="width:74vw;height: 84vw;" src="${data?.receiveSucceedBackgroundImg}" alt="" />
          <div style="position: absolute;bottom: 0;width: 100%;display: flex;flex-direction: column;align-items: center;padding-bottom: 5.5vw;">
            <div style="color: #666;font-size: 3.4vw;display: flex;align-items: center;">
              <span>可前往</span>
              <div id="rightSuccessModalToMyOrder" style="flex: 1;padding: 0 1.8vw;font-weight: bold;color: #111;display: flex;align-items: center;">
                <img
                  style="width: 3.45vw;height: 3.5vw;margin-right: 1.2vw;"
                  src="https://fst1.fuxiaoli.com/images/nfls/mycard.png"
                  alt=""
                />
                <div>我的卡券</div>
              </div>
              <span>进行查看</span>
            </div>
            <img
              id="rightSuccessModalBtn"
              style="display: block;width: 55vw;height: 11vw;margin: 6vw auto 0;"
              src="${data?.receiveSucceedButtonImg}"
              alt=""
            />
            <div style="text-align: center;color: #666;margin-top: 4vw;font-size: 3.4vw;">
             <span id="rightSuccessModalTimeoutData"></span>s后自动关闭</div>
          </div>
        </div>
      </div>
    </div>
    `
    if ($zpt('#rightSuccessModal').length <= 0) {
      $zpt('body').append(str)
      $zpt('#rightSuccessModalTimeoutData').append(this.timeoutData)
      $zpt('body').addClass('v-body-hide')
      $zpt('html').addClass('v-body-hide')
    }
  }

  enableRightPopupFloatModalDrag() {
    const floatModal = document.getElementById('rightPopupFloatModal')
    if (!floatModal) return

    let disX = 0,
      disY = 0

    // 解绑旧事件，防止重复绑定
    floatModal.ontouchstart = null
    floatModal.ontouchmove = null
    floatModal.ontouchend = null

    floatModal.addEventListener(
      'touchstart',
      function (e) {
        if (!e.touches || e.touches.length === 0) return
        disX = e.touches[0].clientX - this.offsetLeft
        disY = e.touches[0].clientY - this.offsetTop
      },
      { passive: false },
    )

    floatModal.addEventListener(
      'touchmove',
      function (e) {
        e.preventDefault()
        if (!e.touches || e.touches.length === 0) return
        // 实时获取窗口尺寸，兼容横竖屏切换
        const cWidth = document.documentElement.clientWidth
        const cHeight = document.documentElement.clientHeight

        let moveX = e.touches[0].clientX - disX
        let moveY = e.touches[0].clientY - disY

        if (moveX < 0) moveX = 0
        else if (moveX > cWidth - this.offsetWidth) moveX = cWidth - this.offsetWidth

        if (moveY < 20)
          moveY = 20 // 顶部留20px
        else if (moveY > cHeight - this.offsetHeight) moveY = cHeight - this.offsetHeight

        this.style.left = moveX + 'px'
        this.style.top = moveY + 'px'
        this.style.right = 'auto'
      },
      { passive: false },
    )

    floatModal.addEventListener(
      'touchend',
      function () {
        // var ele_endx = this.getBoundingClientRect().left
        // if (ele_endx > window.innerWidth / 2 - this.offsetWidth / 2) {
        //   this.style.left = '79vw'
        // } else {
        //   this.style.left = '1vw'
        // }
        // 吸附到右侧
        this.style.right = '0'
        this.style.left = 'auto'

        localStorage.setItem(
          'rightPopupFloatModal',
          JSON.stringify({
            top: this.style.top,
            right: this.style.right,
          }),
        )
      },
      { passive: false },
    )
  }
}
